const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const logger = require('../utils/logger');

// 字段验证函数
const validateFields = (fields) => {
  if (!Array.isArray(fields)) {
    throw new Error('字段必须是数组格式');
  }
  fields.forEach(field => {
    if (!field.field_name || field.description === undefined) {
      throw new Error('字段格式不正确，必须包含 field_name 和 description');
    }
  });
};

const Certificate = sequelize.define('Certificate', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  sequence_number: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      notEmpty: true
    }
  },
  fields: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: [],
    validate: {
      isValidFields(value) {
        validateFields(value);
      }
    }
  },
  qr_code_path: {
    type: DataTypes.STRING,
    allowNull: true
  },
  custom_text: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    defaultValue: 'active',
    allowNull: false,
    validate: {
      isIn: [['active', 'inactive']]
    }
  }
}, {
  tableName: 'certificates',
  timestamps: true,
  underscored: true,
  indexes: [
    {
      name: 'idx_sequence_number',
      unique: true,
      fields: ['sequence_number']
    },
    {
      name: 'idx_status',
      fields: ['status']
    },
    {
      name: 'idx_created_at',
      fields: ['created_at']
    }
  ],
  hooks: {
    beforeValidate: async (certificate) => {
      try {
        if (certificate.fields) {
          validateFields(certificate.fields);
        }
      } catch (error) {
        logger.error('Certificate validation error:', error);
        throw error;
      }
    }
  }
});

module.exports = Certificate; 